import c2s from '~/message/protos/c2s_pb'
import s2c from '~/message/protos/s2c_pb'

let handlerMap = new Map();
let structMap = new Map();
let handlerCloseFunc = null;

export default {
    ws: null,
    onopen(ws, event) {
        console.log('onopen', ws, event);
    },
    onclose(ws, event) {
        if (typeof(handlerCloseFunc) === "function") {
            handlerCloseFunc();
        }
    },
    onmessage(event) {
        let scMsg = s2c.SCMsg.deserializeBinary(event.data)
        if (handlerMap.has(scMsg.getId())) {
            // console.log('onmessage', event.data);
            let handler = handlerMap.get(scMsg.getId());
            let struct = structMap.get(scMsg.getId());
            return handler(struct.deserializeBinary(scMsg.getContent()))
        }
        console.log('skip! handler is not found: ', scMsg.getId());
    },
    init() {
        this.ws = new WebSocket('ws://' + window.admin.mix_websocket)
        this.ws.onmessage = this.onmessage;
        this.ws.onopen = this.onopen;
        this.ws.onclose = this.onclose;
        this.ws.binaryType = 'arraybuffer';
    },
    clear() {
        this.close();
        this.resetHandler();
        handlerCloseFunc = null;
    },
    close() {
        if (this.ws) this.ws.close();
    },
    addHandler(msgId, struct, callback) {
        if (structMap.has(struct)) throw new Error('消息重复定义: ' + msgId);
        if (handlerMap.has(msgId)) throw new Error('回调重复定义: ' + msgId);

        structMap.set(msgId, struct);
        handlerMap.set(msgId, callback);
    },
    resetHandler() {
        handlerMap = new Map();
    },
    send(msgId, msg) {
        let csMsg = new c2s.CSMsg
        csMsg.setId(msgId)
        csMsg.setContent(msg.serializeBinary())
        csMsg.setLen(csMsg.getContent().length)
        this.ws.send(csMsg.serializeBinary())
    },
    addHandlerClose(callback) {
        handlerCloseFunc = callback;
    }
}
